/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;

import org.iosgi.IsolatedFramework;
import org.iosgi.IsolationAdmin;
import org.iosgi.util.io.Streams;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sven Schulz
 */
public class BundleOperation extends AbstractOperation {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(BundleOperation.class);

	public enum Type {
		INSTALL, UNINSTALL
	}

	private final Type type;
	private final String location;

	public BundleOperation(final Type type, final String target,
			final String location) {
		super(target);
		this.type = type;
		this.location = location;
	}

	@Override
	public void perform(IsolationAdmin admin) throws Exception {
		switch (type) {
		case INSTALL: {
			IsolatedFramework fw = admin.getIsolatedFramework(URI.create(this
					.getTarget()));
			byte[] data = null;
			/*
			 * File may not be accessible from remote isolation environment.
			 * Thus, install with prefetched bundle data.
			 */
			if (location.startsWith("file:")) {
				File f = new File(URI.create(location));
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				Streams.drain(new FileInputStream(f), baos).get();
				data = baos.toByteArray();
			}
			fw.installBundle(location, data);
			break;
		}
		case UNINSTALL: {
			Bundle b = admin.getBundle(location);
			if (b == null) {
				LOGGER.warn("bundle with location {} not found", location);
				return;
			}
			b.uninstall();
			break;
		}
		}
	}

	@Override
	public String toString() {
		StringBuilder b = new StringBuilder();
		b.append(super.toString()).append('[').append(type).append(' ')
				.append(location).append(']');
		return b.toString();
	}
}
